package cn.tedu.spring;

import cn.tedu.spring.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Author：程Sir
 * Name： framework
 * Content:
 */
@Component
@ComponentScan("cn.tedu.spring")
@Configuration
@EnableWebMvc
public class SpringMvcConfig implements WebMvcConfigurer {

    private static List<String> url = new ArrayList<String>();
    static {
        url.add("/user/*.html");
        url.add("/user/login.do");
        url.add("/user/toLogin.do");
        url.add("/user/register.do");
        url.add("/user/toRegister.do");
    }
    public void addInterceptors(InterceptorRegistry registry) {
        LoginInterceptor interceptor = new LoginInterceptor();
        registry.addInterceptor(interceptor)
                .addPathPatterns("/user/*")
//                .excludePathPatterns("/user/*.html","/user/login,do","/user/toLogin.do","/user/register.do","/user/toRegister.do");
                // 等价于传入list集合，集合中存储的都是放行路径！
                .excludePathPatterns(url);
    }

    // 配置视图解析器
    @Bean
    public ViewResolver viewResolver(){
        System.out.println("init ThymeleafViewResolver");

        //设置模板保存位置为 /resources/templates/*.html
        ClassLoaderTemplateResolver templateResolver =
                new ClassLoaderTemplateResolver();
        //模版存储文件夹
        templateResolver.setPrefix("/templates/");
        //模版后缀
        templateResolver.setSuffix(".html");
        templateResolver.setCharacterEncoding("UTF-8");
        templateResolver.setTemplateMode(TemplateMode.HTML);
        templateResolver.setCacheable(false);
        //创建模板引擎
        SpringTemplateEngine templateEngine =
                new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);
        templateEngine.setEnableSpringELCompiler(true);
        //创建模版解析器
        ThymeleafViewResolver viewResolver =
                new ThymeleafViewResolver();
        viewResolver.setCharacterEncoding("UTF-8");
        viewResolver.setTemplateEngine(templateEngine);
        return viewResolver;
    }
}
